﻿using WAU.DAL;
using WAU.Models.LogModels;
using Microsoft.Extensions.DependencyInjection;

namespace WAU.Services
{
    /**
     * 由于需要全局记录日志，即该服务必须使用新的数据库连接
     */

    /// <summary>
    /// 日志记录
    /// </summary>
    public class LogService
    {
        /// <summary>
        /// scope 服务工厂
        /// </summary>
        IServiceScopeFactory serviceScopeFactory;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="serviceScopeFactory"></param>
        public LogService(IServiceScopeFactory serviceScopeFactory)
        {
            this.serviceScopeFactory = serviceScopeFactory;            
        }

        /// <summary>
        /// 记录访问日志
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public void LogAccess(LogAccess item)
        {
            ThreadPool.QueueUserWorkItem((_) =>
            {
                try
                {
                    IServiceScope scope = serviceScopeFactory.CreateScope();
                    EssentialLogDbContext logDbContext = scope.ServiceProvider.GetService<EssentialLogDbContext>();
                    logDbContext.Set<LogAccess>().Add(item);
                    logDbContext.SaveChanges();
                }
                catch
                {

                }                
            });
        }

        /// <summary>
        /// 记录业务错误日志
        /// </summary>
        /// <param name="summary"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public void LogBusinessException(string userId, string summary, Exception ex)
        {
            ThreadPool.QueueUserWorkItem((_) =>
            {
                try
                {
                    LogBusinessException item = new LogBusinessException
                    {
                        UserId = userId,
                        Summary = summary,
                        ErrorMsg = ex.Message,
                        ErrorStackTrace = ex.StackTrace,
                        CreateTime = DateTime.Now
                    };

                    IServiceScope scope = serviceScopeFactory.CreateScope();
                    EssentialLogDbContext logDbContext = scope.ServiceProvider.GetService<EssentialLogDbContext>();
                    logDbContext.Set<LogBusinessException>().Add(item);
                    logDbContext.SaveChanges();
                }
                catch
                {

                }
            });
        }
    }
}
